package com.ccjq.shosestore.core.dbmanager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * describe: 数据库连接工具类
 *
 * @author xugang
 * @date 2018/11/1 9:05
 */
public class DbConnection {

	private static final String DRIVER;
	private static final String URL;
	private static final String USERNAME;
	private static final String PASSWORD;

	static {
		DbConfigReader dbConfigReader = new DbConfigReader();
		DRIVER = dbConfigReader.getValue("db.driver");
		URL = dbConfigReader.getValue("db.url");
		USERNAME = dbConfigReader.getValue("db.username");
		PASSWORD = dbConfigReader.getValue("db.password");
	}

	/**
	 * 建立数据库连接
	 *
	 * @return 连接对象
	 */
	public static Connection getConnection() {
		Connection connection = null;

		try {
			Class.forName(DRIVER);
			connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return connection;
	}

	/**
	 * 关闭数据库相关资源
	 *
	 * @param rs   结果集对象
	 * @param st   语句对象
	 * @param conn 连接对象
	 */
	public static void close(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}

			if (st != null) {
				st.close();
			}

			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭数据库相关资源
	 *
	 * @param rs 结果集对象
	 * @param st 语句对象
	 */
	public static void close(ResultSet rs, Statement st) {
		try {
			if (rs != null) {
				rs.close();
			}

			if (st != null) {
				st.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭数据库相关资源
	 *
	 * @param rs 结果集对象
	 */
	public static void close(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭数据库相关资源
	 *
	 * @param st 语句对象
	 */
	public static void close(Statement st) {
		try {
			if (st != null) {
				st.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭数据库连接
	 *
	 * @param conn 连接对象
	 */
	public static void close(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 测试
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(DbConnection.getConnection());
	}
}
